// 页面导航功能
document.addEventListener('DOMContentLoaded', function() {
    const navButtons = document.querySelectorAll('.nav-btn');
    const pages = document.querySelectorAll('.page');
    
    // 导航切换
    navButtons.forEach(button => {
        button.addEventListener('click', function() {
            const targetPage = this.id.replace('Btn', '');

            // 更新按钮状态
            navButtons.forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');

            // 切换页面
            pages.forEach(page => page.classList.remove('active'));
            document.getElementById(targetPage).classList.add('active');

            // 加载对应数据
            if (targetPage === 'user') {
                loadUserInfo();
            } else if (targetPage === 'knowledge') {
                loadKnowledgePoints();
            } else if (targetPage === 'register') {
                initRegisterForm();
            }
        });
    });

    // Hello World 功能
    initHelloWorldFeature();
    
    // 初始化注册功能
    initRegisterForm();
});

// 初始化 Hello World 功能
function initHelloWorldFeature() {
    const helloWorldBtn = document.getElementById('helloWorldBtn');
    const helloWorldOutput = document.getElementById('helloWorldOutput');

    if (helloWorldBtn && helloWorldOutput) {
        helloWorldBtn.addEventListener('click', function() {
            // 在控制台打印
            console.log('Hello World!');

            // 在页面上显示
            helloWorldOutput.innerHTML = '🎉 Hello World! 🎉';

            // 添加动画效果
            helloWorldOutput.style.animation = 'none';
            setTimeout(() => {
                helloWorldOutput.style.animation = 'fadeInBounce 0.6s ease-out';
            }, 10);

            // 按钮点击反馈
            helloWorldBtn.style.transform = 'scale(0.95)';
            setTimeout(() => {
                helloWorldBtn.style.transform = '';
            }, 150);
        });
    }
}

// 加载用户信息
async function loadUserInfo() {
    const userInfoDiv = document.getElementById('userInfo');
    userInfoDiv.innerHTML = '<div class="loading">加载中...</div>';
    
    try {
        const response = await fetch('/api/user');
        const userData = await response.json();
        
        userInfoDiv.innerHTML = `
            <div class="user-info">
                <h3>👤 基本信息</h3>
                <p><strong>姓名:</strong> ${userData.name}</p>
                <p><strong>邮箱:</strong> ${userData.email}</p>
                <p><strong>角色:</strong> ${userData.role}</p>
                <p><strong>加入时间:</strong> ${userData.joinDate}</p>
            </div>
            <div class="user-info">
                <h3>📈 学习进度</h3>
                <p><strong>完成课程:</strong> ${userData.learningProgress.completedCourses} 门</p>
                <p><strong>总积分:</strong> ${userData.learningProgress.totalPoints} 分</p>
                <p><strong>当前等级:</strong> ${userData.learningProgress.currentLevel}</p>
            </div>
        `;
    } catch (error) {
        userInfoDiv.innerHTML = '<div class="error">加载失败，请稍后重试</div>';
        console.error('加载用户信息失败:', error);
    }
}

// 加载知识点列表
async function loadKnowledgePoints() {
    const knowledgeListDiv = document.getElementById('knowledgeList');
    knowledgeListDiv.innerHTML = '<div class="loading">加载中...</div>';
    
    try {
        const response = await fetch('/api/knowledge');
        const knowledgeData = await response.json();
        
        const knowledgeHTML = knowledgeData.map(item => `
            <div class="knowledge-item">
                <div>
                    <h4>${item.title}</h4>
                    <span class="difficulty">${item.difficulty}</span>
                </div>
                <span class="category">${item.category}</span>
            </div>
        `).join('');
        
        knowledgeListDiv.innerHTML = `<div class="knowledge-list">${knowledgeHTML}</div>`;
    } catch (error) {
        knowledgeListDiv.innerHTML = '<div class="error">加载失败，请稍后重试</div>';
        console.error('加载知识点失败:', error);
    }
}

// 初始化注册表单
function initRegisterForm() {
    const registerForm = document.getElementById('registerForm');
    if (!registerForm) return;
    
    // 实时验证
    const usernameInput = document.getElementById('username');
    const emailInput = document.getElementById('email');
    const passwordInput = document.getElementById('password');
    const confirmPasswordInput = document.getElementById('confirmPassword');
    
    // 用户名验证
    usernameInput?.addEventListener('input', function() {
        validateUsername(this.value);
    });
    
    // 邮箱验证
    emailInput?.addEventListener('input', function() {
        validateEmail(this.value);
    });
    
    // 密码验证
    passwordInput?.addEventListener('input', function() {
        validatePassword(this.value);
        if (confirmPasswordInput.value) {
            validateConfirmPassword(confirmPasswordInput.value, this.value);
        }
    });
    
    // 确认密码验证
    confirmPasswordInput?.addEventListener('input', function() {
        validateConfirmPassword(this.value, passwordInput.value);
    });
    
    // 表单提交
    registerForm.addEventListener('submit', handleRegisterSubmit);
}

// 用户名验证
function validateUsername(username) {
    const usernameError = document.getElementById('usernameError');
    const formGroup = document.getElementById('username').closest('.form-group');
    
    if (!username) {
        setFieldError(formGroup, usernameError, '');
        return false;
    }
    
    if (username.length < 3) {
        setFieldError(formGroup, usernameError, '用户名至少需要3个字符');
        return false;
    }
    
    if (username.length > 20) {
        setFieldError(formGroup, usernameError, '用户名不能超过20个字符');
        return false;
    }
    
    if (!/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(username)) {
        setFieldError(formGroup, usernameError, '用户名只能包含字母、数字、下划线和中文');
        return false;
    }
    
    setFieldSuccess(formGroup, usernameError);
    return true;
}

// 邮箱验证
function validateEmail(email) {
    const emailError = document.getElementById('emailError');
    const formGroup = document.getElementById('email').closest('.form-group');
    
    if (!email) {
        setFieldError(formGroup, emailError, '');
        return false;
    }
    
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
        setFieldError(formGroup, emailError, '请输入有效的邮箱地址');
        return false;
    }
    
    setFieldSuccess(formGroup, emailError);
    return true;
}

// 密码验证
function validatePassword(password) {
    const passwordError = document.getElementById('passwordError');
    const formGroup = document.getElementById('password').closest('.form-group');
    
    if (!password) {
        setFieldError(formGroup, passwordError, '');
        return false;
    }
    
    if (password.length < 6) {
        setFieldError(formGroup, passwordError, '密码至少需要6个字符');
        return false;
    }
    
    if (password.length > 50) {
        setFieldError(formGroup, passwordError, '密码不能超过50个字符');
        return false;
    }
    
    setFieldSuccess(formGroup, passwordError);
    return true;
}

// 确认密码验证
function validateConfirmPassword(confirmPassword, password) {
    const confirmPasswordError = document.getElementById('confirmPasswordError');
    const formGroup = document.getElementById('confirmPassword').closest('.form-group');
    
    if (!confirmPassword) {
        setFieldError(formGroup, confirmPasswordError, '');
        return false;
    }
    
    if (confirmPassword !== password) {
        setFieldError(formGroup, confirmPasswordError, '两次输入的密码不一致');
        return false;
    }
    
    setFieldSuccess(formGroup, confirmPasswordError);
    return true;
}

// 设置字段错误状态
function setFieldError(formGroup, errorElement, message) {
    formGroup.classList.remove('success');
    formGroup.classList.add('error');
    errorElement.textContent = message;
}

// 设置字段成功状态
function setFieldSuccess(formGroup, errorElement) {
    formGroup.classList.remove('error');
    formGroup.classList.add('success');
    errorElement.textContent = '';
}

// 处理注册表单提交
async function handleRegisterSubmit(event) {
    event.preventDefault();
    
    const formData = new FormData(event.target);
    const username = formData.get('username');
    const email = formData.get('email');
    const password = formData.get('password');
    const confirmPassword = formData.get('confirmPassword');
    
    // 验证所有字段
    const isUsernameValid = validateUsername(username);
    const isEmailValid = validateEmail(email);
    const isPasswordValid = validatePassword(password);
    const isConfirmPasswordValid = validateConfirmPassword(confirmPassword, password);
    
    if (!isUsernameValid || !isEmailValid || !isPasswordValid || !isConfirmPasswordValid) {
        showRegisterResult('请检查并修正表单中的错误', 'error');
        return;
    }
    
    // 显示加载状态
    const submitBtn = document.getElementById('registerSubmitBtn');
    submitBtn.classList.add('loading');
    submitBtn.disabled = true;
    
    try {
        const response = await fetch('/api/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                username,
                email,
                password
            })
        });
        
        const result = await response.json();
        
        if (response.ok) {
            showRegisterResult('🎉 注册成功！欢迎加入费曼学习平台！', 'success');
            // 清空表单
            event.target.reset();
            // 清除验证状态
            document.querySelectorAll('.form-group').forEach(group => {
                group.classList.remove('success', 'error');
            });
            document.querySelectorAll('.field-error').forEach(error => {
                error.textContent = '';
            });
        } else {
            let errorMessage = '注册失败，请稍后重试';
            if (result.msg === 'Email already exists') {
                errorMessage = '该邮箱已被注册，请使用其他邮箱';
            } else if (result.msg === 'Username already exists') {
                errorMessage = '该用户名已被使用，请选择其他用户名';
            }
            showRegisterResult(errorMessage, 'error');
        }
    } catch (error) {
        console.error('注册请求失败:', error);
        showRegisterResult('网络错误，请检查网络连接后重试', 'error');
    } finally {
        // 恢复按钮状态
        submitBtn.classList.remove('loading');
        submitBtn.disabled = false;
    }
}

// 显示注册结果
function showRegisterResult(message, type) {
    const resultDiv = document.getElementById('registerResult');
    resultDiv.textContent = message;
    resultDiv.className = `register-result ${type}`;
    
    // 滚动到结果位置
    resultDiv.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}